<?php

class users extends Module {
	
	public function __construct () {
		parent::__construct ('users');
	}
	
	public function __default () {
		throw new NotFound;
	}
	
	public function groups () {
		$oTypeUser = TypesController::getInstance()->getTypeByName ('user');
		
		if (isset ($_POST['login']) && $_POST['login'] != ExplaySession::getUser()->getValue ('login')) {
			$sel = new Selection;
			$sel->addType ($oTypeUser);
			$sel->addFilter ('login', $_POST['login']);
			
			$res = $sel->getList ();
			
			if (count ($res)) {
				$oUser = ObjectsController::getInstance()->getObject ($oTypeUser, $res[0][0]);
				
				if (getRequest ('add_admin','bool')) {
					
					if ($oUser->getValue ('group') == 0) {
						$oUser->setValue ('group', 2);
					} else {
						$oUser->setValue ('group', 0);
					}
					
					$oUser->save ();
					
					redirect (HTTP_HOST . '/admin/users/groups');
				} elseif (getRequest ('add_moderator','bool')) {
					
					if ($oUser->getValue ('group') == 1) {
						$oUser->setValue ('group', 2);
					} else {
						$oUser->setValue ('group', 1);
					}
					
					$oUser->save ();
					
					redirect (HTTP_HOST . '/admin/users/groups');
				} 
			}
		}
		
		$sel = new Selection;
		$sel->addType ($oTypeUser);
		$sel->addFilterIn ('group', array (0, 1));
		
		$aObjects = ObjectsController::getInstance()->getObjectsList ($sel->getList ());
		
		$response = new ModuleResponse;
		$response->setTemplate ('users/groups');
		
		foreach ($aObjects as $object) {
			$object->setAttribute ('group', $object->getValue ('group') == 0 ? 'admin' : 'moderator');

			$response->addObject ($object);
		}
		
		return $response;
	}
	
}